<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Opus库测试</title>
</head>
<body>
  <h1>Opus库加载测试</h1>
  <div id="status">检测中...</div>
  <div id="details"></div>

  <!-- Opus库 -->
  <script src="./libopus.js"></script>
  <script src="./opus.js"></script>

  <script>
    async function testOpusLibrary() {
      const statusEl = document.getElementById('status');
      const detailsEl = document.getElementById('details');
      
      let attempts = 0;
      const maxAttempts = 15;

      const checkLibrary = () => {
        attempts++;
        
        const status = {
          OpusEncoder: typeof OpusEncoder,
          OpusApplication: typeof OpusApplication,
          Module: typeof Module,
          _opus_encoder_create: typeof _opus_encoder_create
        };

        console.log(`第${attempts}次检查:`, status);
        detailsEl.innerHTML = `<pre>${JSON.stringify(status, null, 2)}</pre>`;

        if (typeof OpusEncoder !== 'undefined' && 
            typeof OpusApplication !== 'undefined' && 
            typeof Module !== 'undefined' && 
            typeof _opus_encoder_create !== 'undefined') {
          
          statusEl.innerHTML = '✅ Opus库已完全加载！';
          statusEl.style.color = 'green';
          
          try {
            // 测试创建编码器（与后端demo一致：60ms帧，Audio应用）
            const encoder = new OpusEncoder(16000, 1, OpusApplication.Audio, 60);
            console.log('✅ Opus编码器创建成功（60ms帧，Audio应用）');
            
            // 测试编码（60ms @ 16kHz = 960样本）
            const testData = new Float32Array(960);
            testData.fill(0.1);
            const packets = encoder.encode_float(testData);
            console.log('✅ Opus编码测试成功，生成', packets.length, '个数据包');
            console.log('📊 测试数据包大小:', packets[0] ? packets[0].byteLength : 0, 'bytes');
            
            statusEl.innerHTML += '<br/>✅ 编码器测试成功！';
            encoder.destroy();
          } catch (error) {
            console.error('❌ 编码器测试失败:', error);
            statusEl.innerHTML += '<br/>❌ 编码器测试失败: ' + error.message;
            statusEl.style.color = 'red';
          }
          return;
        }

        if (attempts >= maxAttempts) {
          statusEl.innerHTML = '❌ Opus库加载超时';
          statusEl.style.color = 'red';
          return;
        }

        statusEl.innerHTML = `⏳ 等待Opus库加载... (${attempts}/${maxAttempts})`;
        setTimeout(checkLibrary, 1000);
      };

      checkLibrary();
    }

    // 页面加载后开始测试
    window.addEventListener('load', () => {
      setTimeout(testOpusLibrary, 100);
    });
  </script>
</body>
</html>